package com.sxt.bus.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sxt.sys.utils.RandomUtils;
import com.sxt.sys.utils.WebUtils;


@Controller
@RequestMapping("upload")
public class UploadController {
	 @RequestMapping("upload")
	 @ResponseBody
	 public Map<String,Object> addAttachment(MultipartFile mf){
		          String oldName=mf.getOriginalFilename();
				//1,得到服务器里面要保存文件的父路径
				String realPath=WebUtils.getServletContext().getRealPath("/upload");
						//3,得到文件夹名
						String dirName=RandomUtils.createDateStrUseCurrrentDate();
						//4,构造文件夹并判断文件夹是否存在
						File dirFile=new File(realPath,dirName);
						if(!dirFile.exists()){
							//创建文件夹
							dirFile.mkdirs();
						}
						//5,得到文件的新名字
						String newName=RandomUtils.createFileNameUseTime(oldName);
						//6,构造文件
						File file=new File(dirFile,newName);
						//7,保存文件到硬盘
						//使用MultipartFile的方法把mf里面的流写入file文件
							try {
								mf.transferTo(file);
							} catch (IllegalStateException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("path","../upload/"+dirName+"/"+newName);
				
			return map;
		}	
}
